package com.example.dayu521.gateway.filter;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@Profile({"dev", "prototype"})
@Slf4j
public class HandelKT implements GlobalFilter {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    private static final String redis_prefix = "gateway:KT:";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        var req = exchange.getRequest();
        List<String> wk = req.getHeaders().get("wrap-kt");
        if (wk != null && !wk.isEmpty()) {//外部访问
            for(var ip : req.getHeaders().get("X-Real-IP")){
                if(ip!=null&&!ip.isEmpty()) {
                    var key = redis_prefix + ip;
                    String kt_version = redisTemplate.opsForValue().get(key);
                    if (kt_version != null && !kt_version.isEmpty()) {
                        req.mutate().header("VERSION", kt_version).build();
                        break;
                    }
                }
            }
        }
        return chain.filter(exchange/*.mutate().request(req).build()*/);
//        Mono<Void> are= chain.filter(exchange).then(Mono.defer(()->{
        //post intercept
//
//            return Mono.empty();
//        }));
//
//        return are;
    }
}
